﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using CRM.Database.Model;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Mvc;
using System.Net.Mail;
using Utilites;
using DB = CRM.Models.DB;


namespace CRM.Controllers
{
    [Localize]
    public class TCController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        #region Rubrics - moved

        [CheckAccessAttribute]
        public ActionResult Rubrics()
        {
            var rubricsCol = new CRM.Database.Model.RubricsCollection();
            return View(rubricsCol.RubricsList);
            //return View(DB.Rubrics);
        }

        public ActionResult RubricsPartial()
        {
            var rubricsCol = new CRM.Database.Model.RubricsCollection();
            return PartialView("RubricsPartial", rubricsCol.RubricsList);
            //return PartialView("RubricsPartial", DB.Rubrics);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult RubricsPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.Rubrics rubricsItem)
        {
            var rubricsCol = new CRM.Database.Model.RubricsCollection();
            if (ModelState.IsValid)
            {
                rubricsCol.Update(rubricsItem, Request.LogonUserIdentity.Name);
                //DB.RubricsUpdate(rubricsItem);
            }
            return PartialView("RubricsPartial", rubricsCol.RubricsList);
            //return PartialView("RubricsPartial", DB.Rubrics);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult RubricsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.Rubrics rubricsItem)
        {
            var rubricsCol = new CRM.Database.Model.RubricsCollection();
            if (ModelState.IsValid)
            {
                rubricsCol.Delete(rubricsItem);
                //DB.RubricsDelete(rubricsItem);
            }
            return PartialView("RubricsPartial", rubricsCol.RubricsList);
            //return PartialView("RubricsPartial", DB.Rubrics);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult RubricsPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.Rubrics rubricsItem)
        {
            var rubricsCol = new CRM.Database.Model.RubricsCollection();
            if (ModelState.IsValid)
            {
                rubricsItem.Fill();
                rubricsCol.Add(rubricsItem, Request.LogonUserIdentity.Name);
                //DB.RubricsInsert(rubricsItem);
            }
            return PartialView("RubricsPartial", rubricsCol.RubricsList);
            //return PartialView("RubricsPartial", DB.Rubrics);
        }

        #endregion

        #region TrainigAuditoriums - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsAuditoriums()
        {
            var auditoriumsCol = new CRM.Database.Model.TrainingsAuditoriumsCollection();
            return View(auditoriumsCol.TrainingsAuditoriumsList);
            //return View(DB.TrainingsAuditoriums);
        }

        public ActionResult TrainingsAuditoriumsPartial()
        {
            var auditoriumsCol = new CRM.Database.Model.TrainingsAuditoriumsCollection();
            return PartialView("TrainingsAuditoriumsPartial", auditoriumsCol.TrainingsAuditoriumsList);
            //return PartialView("TrainingsAuditoriumsPartial", DB.TrainingsAuditoriums);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsAuditoriumsPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsAuditoriums trainigAuditoriumItem)
        {
            var auditoriumsCol = new CRM.Database.Model.TrainingsAuditoriumsCollection();
            if (ModelState.IsValid)
            {
                trainigAuditoriumItem.Fill();
                auditoriumsCol.Update(trainigAuditoriumItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsAuditoriumsUpdate(trainigAuditoriumItem);
            }
            return PartialView("TrainingsAuditoriumsPartial", auditoriumsCol.TrainingsAuditoriumsList);
            //return PartialView("TrainingsAuditoriumsPartial", DB.TrainingsAuditoriums);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsAuditoriumsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsAuditoriums trainigAuditoriumItem)
        {
            var auditoriumsCol = new CRM.Database.Model.TrainingsAuditoriumsCollection();
            if (ModelState.IsValid)
            {
                auditoriumsCol.Delete(trainigAuditoriumItem);
                //DB.TrainingsAuditoriumsDelete(trainigAuditoriumItem);
            }
            return PartialView("TrainingsAuditoriumsPartial", auditoriumsCol.TrainingsAuditoriumsList);
            //return PartialView("TrainingsAuditoriumsPartial", DB.TrainingsAuditoriums);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsAuditoriumsPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsAuditoriums trainigAuditoriumItem)
        {
            var auditoriumsCol = new CRM.Database.Model.TrainingsAuditoriumsCollection();
            if (ModelState.IsValid)
            {
                trainigAuditoriumItem.Fill();
                auditoriumsCol.Add(trainigAuditoriumItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsAuditoriumsInsert(trainigAuditoriumItem);
            }
            return PartialView("TrainingsAuditoriumsPartial", auditoriumsCol.TrainingsAuditoriumsList);
            //return PartialView("TrainingsAuditoriumsPartial", DB.TrainingsAuditoriums);
        }

        #endregion

        #region TrainingsCenters - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsCenters()
        {
            var tcCol = new CRM.Database.Model.TrainingsCentersCollection();
            return View(tcCol.TrainingsCentersList);
            //return View(DB.TrainingsCenters);
        }

        public ActionResult TrainingsCentersPartial()
        {
            var tcCol = new CRM.Database.Model.TrainingsCentersCollection();
            return PartialView("TrainingsCentersPartial", tcCol.TrainingsCentersList);
            //return PartialView("TrainingsCentersPartial", DB.TrainingsCenters);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCenters trainingsCenterItem)
        {
            var tcCol = new CRM.Database.Model.TrainingsCentersCollection();
            if (ModelState.IsValid)
            {
                tcCol.Update(trainingsCenterItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCentersUpdate(trainingsCenterItem);
            }
            return PartialView("TrainingsCentersPartial", tcCol.TrainingsCentersList);
            //return PartialView("TrainingsCentersPartial", DB.TrainingsCenters);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCenters trainingsCenterItem)
        {
            var tcCol = new CRM.Database.Model.TrainingsCentersCollection();
            if (ModelState.IsValid)
            {
                tcCol.Delete(trainingsCenterItem);
                //DB.TrainingsCentersDelete(trainingsCenterItem);
            }
            return PartialView("TrainingsCentersPartial", tcCol.TrainingsCentersList);
            //return PartialView("TrainingsCentersPartial", DB.TrainingsCenters);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCenters trainingsCenterItem)
        {
            var tcCol = new CRM.Database.Model.TrainingsCentersCollection();
            if (ModelState.IsValid)
            {
                tcCol.Add(trainingsCenterItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCentersInsert(trainingsCenterItem);
            }
            return PartialView("TrainingsCentersPartial", tcCol.TrainingsCentersList);
            //return PartialView("TrainingsCentersPartial", DB.TrainingsCenters);
        }

        #endregion
        
        #region TrainingsCentersTypes - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsCentersTypes()
        {
            var typesCol = new CRM.Database.Model.TrainingsCentersTypesCollection();
            return View(typesCol.TrainingsCentersTypesList);
            //return View(DB.TrainingsCentersTypes);
        }

        public ActionResult TrainingsCentersTypesPartial()
        {
            var typesCol = new CRM.Database.Model.TrainingsCentersTypesCollection();
            return PartialView("TrainingsCentersTypesPartial", typesCol.TrainingsCentersTypesList);
            //return PartialView("TrainingsCentersTypesPartial", DB.TrainingsCentersTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersTypesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCentersTypes trainingsCentersTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingsCentersTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Update(trainingsCentersTypeItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCentersTypesUpdate(trainingsCentersTypeItem);
            }
            return PartialView("TrainingsCentersTypesPartial", typesCol.TrainingsCentersTypesList);
            //return PartialView("TrainingsCentersTypesPartial", DB.TrainingsCentersTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersTypesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCentersTypes trainingsCentersTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingsCentersTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Delete(trainingsCentersTypeItem);
                //DB.TrainingsCentersTypesDelete(trainingsCentersTypeItem);
            }
            return PartialView("TrainingsCentersTypesPartial", typesCol.TrainingsCentersTypesList);
            //return PartialView("TrainingsCentersTypesPartial", DB.TrainingsCentersTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCentersTypesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCentersTypes trainingsCentersTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingsCentersTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Add(trainingsCentersTypeItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCentersTypesInsert(trainingsCentersTypeItem);
            }
            return PartialView("TrainingsCentersTypesPartial", typesCol.TrainingsCentersTypesList);
            //return PartialView("TrainingsCentersTypesPartial", DB.TrainingsCentersTypes);
        }

        #endregion

        #region TrainingCoursesStatuses - moved

        [CheckAccessAttribute]
        public ActionResult TrainingCoursesStatuses()
        {
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            return View(statusesCol.TrainingCoursesStatusesList);
            //return View(DB.TrainingCoursesStatuses);
        }

        public ActionResult TrainingCoursesStatusesPartial()
        {
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            return PartialView("TrainingCoursesStatusesPartial", statusesCol.TrainingCoursesStatusesList);
            //return PartialView("TrainingCoursesStatusesPartial", DB.TrainingCoursesStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesStatusesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesStatuses trainingCoursesStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            if (ModelState.IsValid)
            {
                trainingCoursesStatusItem.Fill();
                statusesCol.Update(trainingCoursesStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingCoursesStatusesUpdate(trainingCoursesStatusItem);
            }
            return PartialView("TrainingCoursesStatusesPartial", statusesCol.TrainingCoursesStatusesList);
            //return PartialView("TrainingCoursesStatusesPartial", DB.TrainingCoursesStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesStatusesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesStatuses trainingCoursesStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Delete(trainingCoursesStatusItem);
                //DB.TrainingCoursesStatusesDelete(trainingCoursesStatusItem);
            }
            return PartialView("TrainingCoursesStatusesPartial", statusesCol.TrainingCoursesStatusesList);
            //return PartialView("TrainingCoursesStatusesPartial", DB.TrainingCoursesStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesStatusesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesStatuses trainingCoursesStatusItem)
        {
                trainingCoursesStatusItem.Fill();
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            if (ModelState.IsValid)
            {
                trainingCoursesStatusItem.Fill();
                statusesCol.Add(trainingCoursesStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingCoursesStatusesInsert(trainingCoursesStatusItem);
            }
            return PartialView("TrainingCoursesStatusesPartial", statusesCol.TrainingCoursesStatusesList);
            //return PartialView("TrainingCoursesStatusesPartial", DB.TrainingCoursesStatuses);
        }

        #endregion

        #region TrainingCoursesTypes - moved

        [CheckAccessAttribute]
        public ActionResult TrainingCoursesTypes()
        {
            var typesCol = new CRM.Database.Model.TrainingCoursesTypesCollection();
            return View(typesCol.TrainingCoursesTypesList);
            //return View(DB.TrainingCoursesTypes);
        }

        public ActionResult TrainingCoursesTypesPartial()
        {
            var typesCol = new CRM.Database.Model.TrainingCoursesTypesCollection();
            return PartialView("TrainingCoursesTypesPartial", typesCol.TrainingCoursesTypesList);
            //return PartialView("TrainingCoursesTypesPartial", DB.TrainingCoursesTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesTypesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesTypes trainingCoursesTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingCoursesTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Update(trainingCoursesTypeItem, Request.LogonUserIdentity.Name);
                //DB.TrainingCoursesTypesUpdate(trainingCoursesTypeItem);
            }
            return PartialView("TrainingCoursesTypesPartial", typesCol.TrainingCoursesTypesList);
            //return PartialView("TrainingCoursesTypesPartial", DB.TrainingCoursesTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesTypesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesTypes trainingCoursesTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingCoursesTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Delete(trainingCoursesTypeItem);
               // DB.TrainingCoursesTypesDelete(trainingCoursesTypeItem);
            }
            return PartialView("TrainingCoursesTypesPartial", typesCol.TrainingCoursesTypesList);
            //return PartialView("TrainingCoursesTypesPartial", DB.TrainingCoursesTypes);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingCoursesTypesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingCoursesTypes trainingCoursesTypeItem)
        {
            var typesCol = new CRM.Database.Model.TrainingCoursesTypesCollection();
            if (ModelState.IsValid)
            {
                typesCol.Add(trainingCoursesTypeItem, Request.LogonUserIdentity.Name);
                //DB.TrainingCoursesTypesInsert(trainingCoursesTypeItem);
            }
            return PartialView("TrainingCoursesTypesPartial", typesCol.TrainingCoursesTypesList);
            //return PartialView("TrainingCoursesTypesPartial", DB.TrainingCoursesTypes);
        }

        #endregion

        #region TrainingParticipantsStatuses - moved

        [CheckAccessAttribute]
        public ActionResult TrainingParticipantsStatuses()
        {
            var statusesCol = new CRM.Database.Model.TrainingParticipantsStatusesCollection();
            return View(statusesCol.TrainingParticipantsStatusesList);
            //return View(DB.TrainingParticipantsStatuses);
        }

        public ActionResult TrainingParticipantsStatusesPartial()
        {
            var statusesCol = new CRM.Database.Model.TrainingParticipantsStatusesCollection();
            return PartialView("TrainingParticipantsStatusesPartial", statusesCol.TrainingParticipantsStatusesList);
            //return PartialView("TrainingParticipantsStatusesPartial", DB.TrainingParticipantsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingParticipantsStatusesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingParticipantsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Update(trainingParticipantsStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingParticipantsStatusesUpdate(trainingParticipantsStatusItem);
            }
            return PartialView("TrainingParticipantsStatusesPartial", statusesCol.TrainingParticipantsStatusesList);
            //return PartialView("TrainingParticipantsStatusesPartial", DB.TrainingParticipantsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingParticipantsStatusesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingParticipantsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Delete(trainingParticipantsStatusItem);
                //DB.TrainingParticipantsStatusesDelete(trainingParticipantsStatusItem);
            }
            return PartialView("TrainingParticipantsStatusesPartial", statusesCol.TrainingParticipantsStatusesList);
            //return PartialView("TrainingParticipantsStatusesPartial", DB.TrainingParticipantsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingParticipantsStatusesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingParticipantsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Add(trainingParticipantsStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingParticipantsStatusesInsert(trainingParticipantsStatusItem);
            }
            return PartialView("TrainingParticipantsStatusesPartial", statusesCol.TrainingParticipantsStatusesList);
            //return PartialView("TrainingParticipantsStatusesPartial", DB.TrainingParticipantsStatuses);
        }

        #endregion

        #region TrainingsPlaces - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsPlaces()
        {
            var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            return View(placesCol.TrainingsPlacesList);
            //return View(DB.TrainingsPlaces);
        }

        public ActionResult TrainingsPlacesPartial()
        {
            var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            return PartialView("TrainingsPlacesPartial", placesCol.TrainingsPlacesList);
            //return PartialView("TrainingsPlacesPartial", DB.TrainingsPlaces);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlacesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsPlaces trainingsPlaceItem)
        {
            var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            if (ModelState.IsValid)
            {
                trainingsPlaceItem.Fill();
                placesCol.Update(trainingsPlaceItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsPlacesUpdate(trainingsPlaceItem);
            }
            return PartialView("TrainingsPlacesPartial", placesCol.TrainingsPlacesList);
            //return PartialView("TrainingsPlacesPartial", DB.TrainingsPlaces);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlacesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsPlaces trainingsPlaceItem)
        {
            var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            if (ModelState.IsValid)
            {
                placesCol.Delete(trainingsPlaceItem);
                //DB.TrainingsPlacesDelete(trainingsPlaceItem);
            }
            return PartialView("TrainingsPlacesPartial", placesCol.TrainingsPlacesList);
            //return PartialView("TrainingsPlacesPartial", DB.TrainingsPlaces);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlacesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsPlaces trainingsPlaceItem)
        {
            var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            if (ModelState.IsValid)
            {
                trainingsPlaceItem.Fill();
                placesCol.Add(trainingsPlaceItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsPlacesInsert(trainingsPlaceItem);
            }
            return PartialView("TrainingsPlacesPartial", placesCol.TrainingsPlacesList);
            //return PartialView("TrainingsPlacesPartial", DB.TrainingsPlaces);
        }

        #endregion

        #region TrainingRequestsStatuses - moved

        [CheckAccessAttribute]
        public ActionResult TrainingRequestsStatuses()
        {
            var statusesCol = new CRM.Database.Model.TrainingRequestsStatusesCollection();
            return View(statusesCol.TrainingRequestsStatusesList);
            //return View(DB.TrainingRequestsStatuses);
        }

        public ActionResult TrainingRequestsStatusesPartial()
        {
            var statusesCol = new CRM.Database.Model.TrainingRequestsStatusesCollection();
            return PartialView("TrainingRequestsStatusesPartial", statusesCol.TrainingRequestsStatusesList);
            //return PartialView("TrainingRequestsStatusesPartial", DB.TrainingRequestsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingRequestsStatusesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingRequestsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Update(trainingRequestsStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingRequestsStatusesUpdate(trainingRequestsStatusItem);
            }
            return PartialView("TrainingRequestsStatusesPartial", statusesCol.TrainingRequestsStatusesList);
            //return PartialView("TrainingRequestsStatusesPartial", DB.TrainingRequestsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingRequestsStatusesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingRequestsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Delete(trainingRequestsStatusItem);
                //DB.TrainingRequestsStatusesDelete(trainingRequestsStatusItem);
            }
            return PartialView("TrainingRequestsStatusesPartial", statusesCol.TrainingRequestsStatusesList);
            //return PartialView("TrainingRequestsStatusesPartial", DB.TrainingRequestsStatuses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingRequestsStatusesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            var statusesCol = new CRM.Database.Model.TrainingRequestsStatusesCollection();
            if (ModelState.IsValid)
            {
                statusesCol.Add(trainingRequestsStatusItem, Request.LogonUserIdentity.Name);
                //DB.TrainingRequestsStatusesInsert(trainingRequestsStatusItem);
            }
            return PartialView("TrainingRequestsStatusesPartial", statusesCol.TrainingRequestsStatusesList);
            //return PartialView("TrainingRequestsStatusesPartial", DB.TrainingRequestsStatuses);
        }

        #endregion

        #region TrainingsTrainers - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsTrainers()
        {
            var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            return View(trainersCol.TrainingsTrainersList);
            //return View(DB.TrainingsTrainers);
        }

        public ActionResult TrainingsTrainersPartial()
        {
            var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            return PartialView("TrainingsTrainersPartial", trainersCol.TrainingsTrainersList);
            //return PartialView("TrainingsTrainersPartial", DB.TrainingsTrainers);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsTrainersPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsTrainers trainingsTrainerItem)
        {
            var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            if (ModelState.IsValid)
            {
                trainingsTrainerItem.Fill();
                trainersCol.Update(trainingsTrainerItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsTrainersUpdate(trainingsTrainerItem);
            }
            return PartialView("TrainingsTrainersPartial", trainersCol.TrainingsTrainersList);
            //return PartialView("TrainingsTrainersPartial", DB.TrainingsTrainers);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsTrainersPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsTrainers trainingsTrainerItem)
        {
            var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            if (ModelState.IsValid)
            {
                trainersCol.Delete(trainingsTrainerItem);
                //DB.TrainingsTrainersDelete(trainingsTrainerItem);
            }
            return PartialView("TrainingsTrainersPartial", trainersCol.TrainingsTrainersList);
            //return PartialView("TrainingsTrainersPartial", DB.TrainingsTrainers);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsTrainersPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsTrainers trainingsTrainerItem)
        {
            var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            if (ModelState.IsValid)
            {
                trainingsTrainerItem.Fill();
                trainersCol.Add(trainingsTrainerItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsTrainersInsert(trainingsTrainerItem);
            }
            return PartialView("TrainingsTrainersPartial", trainersCol.TrainingsTrainersList);
            //return PartialView("TrainingsTrainersPartial", DB.TrainingsTrainers);
        }

        #endregion

        #region TrainingsCourses - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsCourses()
        {
            var coursesCol = new TrainingsCoursesCollection();
            return View(coursesCol.TrainingsCoursesList);
            //return View(DB.TrainingsCourses);
        }

        public ActionResult TrainingsCoursesPartial()
        {
            var coursesCol = new TrainingsCoursesCollection();
            return PartialView("TrainingsCoursesPartial", coursesCol.TrainingsCoursesList);
            //return PartialView("TrainingsCoursesPartial", DB.TrainingsCourses);
        }

        [CheckAccessAttribute]
        public ActionResult TrainingsCoursesList()
        {
            var coursesCol = new TrainingsCoursesCollection();
            return View(coursesCol.TrainingsCoursesList.OrderByDescending(p => p.IdTrainingsCourse).ToList());
            //return View(DB.TrainingsCourses.OrderByDescending(p => p.IdTrainingsCourse));
        }

        public ActionResult TrainingsCoursesListPartial()
        {
            var coursesCol = new TrainingsCoursesCollection();
            return PartialView("TrainingsCoursesListPartial", coursesCol.TrainingsCoursesList.OrderByDescending(p => p.IdTrainingsCourse).ToList());
            //return PartialView("TrainingsCoursesListPartial", DB.TrainingsCourses.OrderByDescending(p => p.IdTrainingsCourse));
        }

        [HttpGet]
        public ActionResult TrainingsCoursesEdit(int idTrainingsCourse)
        {
            var coursesCol = new TrainingsCoursesCollection();
            var courseItem = (TrainingsCourses)coursesCol.GetItemById(idTrainingsCourse);
            //TrainingsCourses courseItem = DB.GetTrainingsCoursebyId(idTrainingsCourse);
            if (courseItem == null)
            {
                var rubricsCol = new RubricsCollection();
                var rubric = rubricsCol.RubricsActiveList.First();
                int rubricId = 0;
                if (rubric != null)
                    rubricId = rubric.IdRubric;
                courseItem = new TrainingsCourses
                                 {
                                     IdTrainingsCourse = -1,
                                     IdRubric = rubricId,
                                     //IdRubric = DB.RubricsActive.First().IdRubric,
                                     //IdTrainingCoursesType = DB.TrainingCoursesTypesActive.First().IdTrainingCoursesType,
                                     Name = " ",
                                     CourseTypes = "Плановый"
                                 };
            }
            return View("TrainingsCoursesEdit", courseItem);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCoursesEdit([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsCourses trainingsCourseItem)
        {
            var user = Request.LogonUserIdentity.Name;
            var coursesCol = new TrainingsCoursesCollection();
            var trainersCol = new TrainingsTrainersCollection();
            var typesCol = new TrainingCoursesTypesCollection();
            var placesCol = new TrainingsPlacesCollection();
            var auditoriumsCol = new TrainingsAuditoriumsCollection();
            
            //Изменение cуществующего курса
            if (trainingsCourseItem.IdTrainingsCourse > 0)
            {
                //Изменение курса без связей и таблицами многие к многим
                coursesCol.Update(trainingsCourseItem, user);
                //DB.TrainingsCoursesUpdate(trainingsCourseItem);

                //Изменение списка тренеров
                var trainersList = trainersCol.GetTrainersFromString(trainingsCourseItem.Trainers);
                trainingsCourseItem.UpdateTrainersList(trainersList, user);
                //var trainersList = DB.GetTrainersFromString(trainingsCourseItem.Trainers);
                //DB.TrainingsCoursesEditTrainers(trainingsCourseItem, trainersList);

                //Изменение списка площадок
                var placesList = placesCol.GetPlacesFromString(trainingsCourseItem.Places);
                trainingsCourseItem.UpdatePlacesList(placesList, user);
                //var placesList = DB.GetPlacesFromString(trainingsCourseItem.Places);
                //DB.TrainingsCoursesEditPlaces(trainingsCourseItem, placesList);

                //Изменение списка целевых аудиторий
                var auditoriumsList = auditoriumsCol.GetAuditoriumsFromString(trainingsCourseItem.Auditoriums);
                trainingsCourseItem.UpdateAuditoriumsList(auditoriumsList, user);
                //var auditoriumsList = DB.GetAuditoriumsFromString(trainingsCourseItem.Auditoriums);
                //DB.TrainingsCoursesEditAuditoriums(trainingsCourseItem, auditoriumsList);
            }
            //DB.Save();

            //Создание нового курса
            if(trainingsCourseItem.IdTrainingsCourse == -1)
            {
                //Проверка наличия названия у курса
                if (String.IsNullOrEmpty(trainingsCourseItem.Name))
                    trainingsCourseItem.Name = "Без названия";

                //заполнить оставшиеся пропущенные значения пробелами
                trainingsCourseItem.Fill();

                //Добавление чистого курса без связей
                coursesCol.Add(trainingsCourseItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCoursesInsert(trainingsCourseItem);

                //Получение списка тренеров из строки
                var trainersList = trainersCol.GetTrainersFromString(trainingsCourseItem.Trainers);
                //var trainersList = DB.GetTrainersFromString(trainingsCourseItem.Trainers);

                //Запись тренеров в базу
                trainingsCourseItem.AddTrainersList(trainersList, user);
                //DB.TrainingsCoursesAddTrainers(trainingsCourseItem, trainersList);

                //Получение типов курсов из строки
                var coursesTypesList = typesCol.GetCoursesTypesFromString(trainingsCourseItem.CourseTypes);
                //var coursesTypesList = DB.GetCoursesTypesFromString(trainingsCourseItem.CourseTypes);

                //Добавление типов курсов к новому курсу в базе
                trainingsCourseItem.AddTypesList(coursesTypesList, user);
                //DB.TrainingsCoursesAddCoursesTypes(trainingsCourseItem, coursesTypesList);

                //Получание списка площадок из строки
                var placesList = placesCol.GetPlacesFromString(trainingsCourseItem.Places);
                //var placesList = DB.GetPlacesFromString(trainingsCourseItem.Places);

                //Запись площадок в базу
                trainingsCourseItem.AddPlacesList(placesList, user);
                //DB.TrainingsCoursesAddPlaces(trainingsCourseItem, placesList);

                //Получение аудиторий из строки
                var auditoriumsList = auditoriumsCol.GetAuditoriumsFromString(trainingsCourseItem.Auditoriums);
                //var auditoriumsList = DB.GetAuditoriumsFromString(trainingsCourseItem.Auditoriums);

                //Добавление целевых аудиторий к новому курсу в базе
                trainingsCourseItem.AddAuditoriumsList(auditoriumsList, user);
                //DB.TrainingsCoursesAddAuditoriums(trainingsCourseItem, auditoriumsList);

            }
            //DB.Save();
            return RedirectToAction("TrainingsCoursesList");
        }

        public ActionResult TrainingsCoursesDelete(int idTrainingsCourse)
        {
            var coursesCol = new CRM.Database.Model.TrainingsCoursesCollection();
            var course = (CRM.Database.Model.TrainingsCourses)coursesCol.GetItemById(idTrainingsCourse);
            //var course = DB.GetTrainingsCoursebyId(idTrainingsCourse);
            //if (ModelState.IsValid))
            if (course != null)
            {
                coursesCol.Delete(course);
                //DB.TrainingsCoursesDelete(course);
            }
            return RedirectToAction("TrainingsCoursesList");
        }
        
        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCoursesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsCourses trainingsCourseItem)
        {
            var coursesCol = new CRM.Database.Model.TrainingsCoursesCollection();
            if (ModelState.IsValid)
            {
                //DB.TrainingsCoursesUpdate(trainingsCourseItem);
            }
            return PartialView("TrainingsCoursesPartial", coursesCol.TrainingsCoursesList);
            //return PartialView("TrainingsCoursesPartial", DB.TrainingsCourses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCoursesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsCourses trainingsCourseItem)
        {
            var coursesCol = new CRM.Database.Model.TrainingsCoursesCollection();
            if (ModelState.IsValid)
            {
                coursesCol.Delete(trainingsCourseItem);
                //DB.TrainingsCoursesDelete(trainingsCourseItem);
            }
            return PartialView("TrainingsCoursesPartial", coursesCol.TrainingsCoursesList);
            //return PartialView("TrainingsCoursesPartial", DB.TrainingsCourses);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCoursesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsCourses trainingsCourseItem)
        {
            var coursesCol = new CRM.Database.Model.TrainingsCoursesCollection();
            if (ModelState.IsValid)
            {
                //DB.TrainingsCoursesInsert(trainingsCourseItem);
            }
            return PartialView("TrainingsCoursesPartial", coursesCol.TrainingsCoursesList);
            //return PartialView("TrainingsCoursesPartial", DB.TrainingsCourses);
        }

        /// <summary>
        /// Отображение списка курсов для заявок
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public ActionResult TrainingsRemoteCoursesRequest(int customerId)
        {
            return View(customerId);
        }

        public ActionResult TrainingsRemoteCoursesRequestPartial(int customerId)
        {
            return PartialView(customerId);
        }

        #endregion

        #region TrainingsSchedules - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsSchedules()
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            return View(schedulesCol.TrainingsSchedulesList);
            //return View(DB.TrainingsSchedules.OrderByDescending(p => p.PlannedDate));
        }

        public ActionResult TrainingsSchedulesPartial()
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            return PartialView("TrainingsSchedulesPartial", schedulesCol.TrainingsSchedulesList);
            //return PartialView("TrainingsSchedulesPartial", DB.TrainingsSchedules.OrderByDescending(p => p.PlannedDate));
        }

        [CheckAccessAttribute]
        public ActionResult TrainingsSchedulesEdit(int idTrainingsSchedule)
        {
            var schedulesCol = new TrainingsSchedulesCollection();
            var coursesCol = new TrainingsCoursesCollection();
            var regionsCol = new profineRegionsCollection();
            var typesCol = new TrainingCoursesTypesCollection();
            //создание нового расписания
            if (idTrainingsSchedule == -1)
            {
                var scheduleItem = new TrainingsSchedules();
                //scheduleItem.PlannedDate = new DateTime(1900, 1, 1);
                scheduleItem.PlannedDate = DateTime.Now;
                if (regionsCol.profineRegionsList.Count > 0)
                    scheduleItem.IdProfineRegion = regionsCol.profineRegionsList.First().IdProfineRegion;
                //scheduleItem.IdProfineRegion = DB.profineRegionsActive.FirstOrDefault().IdProfineRegion;

                var coursesList = coursesCol.FullDefinedCourses;
                if (coursesList.Count < 1)
                    return RedirectToAction("TrainingsSchedules", new {idTrainingsSchedule = 0});
                //var coursesList = DB.GetFullDefinedCourses();

                //scheduleItem.IdTrainingsCource = coursesList.Max(p => p.IdTrainingsCourse);
                scheduleItem.IdTrainingsCource = coursesList.OrderBy(p => p.Name).First().IdTrainingsCourse;

                //var trainerItem = DB.GetTrainingsTrainersListByCourseId(scheduleItem.IdTrainingsCource).FirstOrDefault();
                //if (trainerItem != null) scheduleItem.IdTrainingsTrainer = trainerItem.IdTrainingsTrainer;
                //var placeItem = DB.GetTrainingsPlacesListByCourseId(scheduleItem.IdTrainingsCource).FirstOrDefault();
                //if (placeItem != null) scheduleItem.IdTrainingsPlace = placeItem.IdTrainingsPlace;

                var courseTypeItem = typesCol.GetTrainingsCoursesTypesByCourseId(scheduleItem.IdTrainingsCource).FirstOrDefault();
                //var courseTypeItem = DB.GetTrainingsCoursesTypesByCourseId(scheduleItem.IdTrainingsCource).FirstOrDefault();)
                if (courseTypeItem != null) scheduleItem.IdTrainingCoursesType = courseTypeItem.IdTrainingCoursesType;

                return View("TrainingsSchedulesEdit", scheduleItem);
            }

            //редактирование существующего
            if(idTrainingsSchedule > 0)
            {
                var scheduleItem = (TrainingsSchedules)schedulesCol.GetItemById(idTrainingsSchedule);
                //var scheduleItem = DB.GetTrainingsSchedulebyId(idTrainingsSchedule);)
                return View("TrainingsSchedulesEdit", scheduleItem);
            }
            return RedirectToAction("TrainingsSchedules");
        }

        public ActionResult TrainingsSchedulesDelete(int idTrainingsSchedule)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            var requestsCol = new CRM.Database.Model.TrainingsRequestsCollection();
            if (idTrainingsSchedule > 0)
            {
                var requestList = (CRM.Database.Model.TrainingsRequests)requestsCol.GetItemById(idTrainingsSchedule);
                //var requestList = DB.GetTrainingsRequestesByScheduleId(idTrainingsSchedule);
                if (requestList != null)
                {
                    var error = "Ошибка! Невозможно удалить выбранное расписание т.к. найдены связанные с ним заявки.";
                    ViewData["Error"] = error;
                    return View(schedulesCol.TrainingsSchedulesList);
                    //return View(DB.TrainingsSchedules);
                }
                var scheduleItem = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById(idTrainingsSchedule);
                //var scheduleItem = DB.GetTrainingsSchedulebyId(idTrainingsSchedule);
                if(scheduleItem != null)
                    schedulesCol.Delete(scheduleItem);
                    //DB.TrainingsSchedulesDelete(scheduleItem);
            }
            if(idTrainingsSchedule == 0)
            {
                string error = "Ошибка! Не найдено ни одного подходящего курса в каталоге.";
                ViewData["Error"] = error;
                return View(schedulesCol.TrainingsSchedulesList);
            }
            return RedirectToAction("TrainingsSchedules");
        }

        /// <summary>
        /// Отмена расписания
        /// </summary>
        /// <param name="idTrainingsSchedule"></param>
        /// <returns></returns>
        public ActionResult TrainingsSchedulesCancel(int idTrainingsSchedule)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            if (idTrainingsSchedule > 0)
            {
                var schedule = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById(idTrainingsSchedule);
                //var schedule = DB.GetTrainingsSchedulebyId(idTrainingsSchedule);
                if(schedule != null)
                {
                    schedule.IdTrainingCoursesStatus = 6;
                    schedulesCol.Update(schedule, Request.LogonUserIdentity.Name);
                    //DB.TrainingsSchedulesUpdate(schedule);
                }
            }
            return RedirectToAction("TrainingsSchedules");
        }

        public ActionResult TrainingsSchedulesEditCoursesPartial()
        {
            return PartialView();
        }

        public ActionResult TrainingsSchedulesEditTrainersPartial()
        {
            int country = (Request.Params["Country"] != null) ? int.Parse(Request.Params["Country"]) : -1;
            var schedule = new TrainingsSchedules {IdTrainingsCource = country};
            return PartialView(schedule);
        }

        public ActionResult TrainingsSchedulesEditPlacesPartial()
        {
            int country = (Request.Params["Country"] != null) ? int.Parse(Request.Params["Country"]) : -1;

            var schedule = new CRM.Database.Model.TrainingsSchedules {IdTrainingsCource = country};
            return PartialView(schedule);
            //return PartialView(new TrainingsSchedules { IdTrainingsCource = country, IdTrainingsPlace = 0, IdTrainingsTrainer = 0});
            //return PartialView(DB.TrainingsSchedules.FirstOrDefault());
        }

        public ActionResult TrainingsSchedulesEditCourseTypePartial()
        {
            int country = (Request.Params["Country"] != null) ? int.Parse(Request.Params["Country"]) : -1;

            var schedule = new CRM.Database.Model.TrainingsSchedules {IdTrainingsCource = country};
            return PartialView(schedule);
            //return PartialView(new TrainingsSchedules { IdTrainingsCource = country, IdTrainingsPlace = 0, IdTrainingsTrainer = 0 });
            //return PartialView(new TrainingsSchedules { IdTrainingsCource = country });
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsSchedulesEdit([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsSchedules scheduleItem)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            var user = Request.LogonUserIdentity.Name;
            //Добавление нового расписания
            if (scheduleItem.IdTrainingsSchedule == -1)
            {
                //scheduleItem.IdTrainingCoursesStatus = DB.GetCourseStatusIdByDate(scheduleItem.PlannedDate);
                scheduleItem.IdTrainingCoursesStatus = 1;
                schedulesCol.Add(scheduleItem, user);
                //DB.TrainingsSchedulesInsert(scheduleItem);
            }
            //изменение существующего расписания
            //коллекция статусов
            var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            if (scheduleItem.IdTrainingsSchedule > 0)
            {
                if (scheduleItem.IdTrainingCoursesStatus <= 1)
                    scheduleItem.IdTrainingCoursesStatus = statusesCol.GetStatusIdByDate(scheduleItem.PlannedDate);
                    //scheduleItem.IdTrainingCoursesStatus = DB.GetCourseStatusIdByDate(scheduleItem.PlannedDate);
                schedulesCol.Update(scheduleItem, user);
                //DB.TrainingsSchedulesUpdate(scheduleItem);
            }
            return RedirectToAction("TrainingsSchedules");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsSchedulesCourseEdit([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsSchedules scheduleItem)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            if (scheduleItem == null)
                return RedirectToAction("TrainingsSchedules");
            return View("TrainingsSchedulesEdit", scheduleItem);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsSchedulesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsSchedules trainingsSchedulesItem)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            if (ModelState.IsValid)
            {
                //DB.TrainingsSchedulesUpdate(trainingsSchedulesItem);
            }
            return PartialView("TrainingsSchedulesPartial", schedulesCol.TrainingsSchedulesList);
            //return PartialView("TrainingsSchedulesPartial", DB.TrainingsSchedules);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsSchedulesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsSchedules trainingsSchedulesItem)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            if (ModelState.IsValid)
            {
                //DB.TrainingsSchedulesDelete(trainingsSchedulesItem);
            }
            return PartialView("TrainingsSchedulesPartial", schedulesCol.TrainingsSchedulesList);
            //return PartialView("TrainingsSchedulesPartial", DB.TrainingsSchedules);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsSchedulesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsSchedules trainingsSchedulesItem)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            if (ModelState.IsValid)
            {
                //DB.TrainingsSchedulesInsert(trainingsSchedulesItem);
            }
            return PartialView("TrainingsSchedulesPartial", schedulesCol.TrainingsSchedulesList);
            //return PartialView("TrainingsSchedulesPartial", DB.TrainingsSchedules);
        }

        /// <summary>
        /// отображение расписания для плановых заявок
        /// </summary>
        /// <returns></returns>
        public ActionResult TraningsSchedulesRequest(int customerId)
        {
            return View(customerId);
        }

        /// <summary>
        /// частичное отображение расписания для плановых заявок
        /// </summary>
        /// <returns></returns>
        public ActionResult TraningsSchedulesRequestPartial(int customerId)
        {
            return PartialView(customerId);
        }

        public ActionResult TrainingsWebinarRequest(int customerId)
        {
            return View(customerId);
        }

        /// <summary>
        /// частичное отображение расписания для вебинаров
        /// </summary>
        /// <returns></returns>
        public ActionResult TrainingsWebinarRequestPartial(int customerId)
        {
            return PartialView(customerId);
        }

        #endregion

        #region TrainingsRequests - moved

        #region General - moved

        //Основной список заявок - отображение таблицы

        [CheckAccessAttribute]
        public ActionResult TrainingsRequests()
        {
            var requestsCol = new CRM.Database.Model.TrainingsRequestsCollection();
            return View(requestsCol.TrainingsRequestsList);
            //return View(DB.TrainingsRequests.OrderByDescending(p => p.IdTrainingsRequest));
        }

        public ActionResult TrainingsRequestsPartial()
        {
            var requestsCol = new TrainingsRequestsCollection();
            return PartialView("TrainingsRequestsPartial", requestsCol.TrainingsRequestsList);
            //return PartialView("TrainingsRequestsPartial", DB.TrainingsRequests.OrderByDescending(p => p.IdTrainingsRequest));
        }

        //Частичное отображение участников расширенной заявки с возможностью редактирования списка
        //Используется во всех типах заявок при создании и редактировании

        public ActionResult TrainingsParticipantsPartial(int key)
        {
            var requestExt = DB.TrainingsRequestsExtDic[key];
            return PartialView(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsNew, int key)
        {
            participantsNew.IdUser = Request.LogonUserIdentity.Name;
            if (participantsNew.IdTrainingsParticipantsStatus == 0)
                participantsNew.IdTrainingsParticipantsStatus = 2;
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.AddParticipant(participantsNew);
            //DB.TrainingsParticipantsAdd(participantsNew, key);)
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsEdit, int key)
        {
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.UpdateParticipant(participantsEdit);
            //DB.TrainingsParticipantsEdit(participantsEdit, key);
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
        {
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.DeleteParticipant(participantsDel);
            //DB.TrainingsParticipantsDel(participantsDel, key);)
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }
        
        //Частичные отображение для каскадных комбобоксов

        public ActionResult TrainingsRequestLEPartial(int key)
        {
            var requestExt = DB.TrainingsRequestsExtDic[key];
            return PartialView(requestExt);
        }

        public ActionResult TrainingsRequestContactPartial(int key)
        {
            var idLegalEntity = (Request.Params["LE"] != null) ? int.Parse(Request.Params["LE"]) : -1;
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.IdLegalEntity = idLegalEntity;
            requestExt.Request.IdLegalEntity = idLegalEntity;
            return PartialView(requestExt);
        }

        //------------------------

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsRequestsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequests request)
        {
            var requestsCol = new CRM.Database.Model.TrainingsRequestsCollection();
            requestsCol.Delete(request);
            return PartialView("TrainingsRequestsPartial", requestsCol.TrainingsRequestsList);
        }

        /// <summary>
        /// Просмотр подродностей заявки
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestDetails(int idTrainingsRequest)
        {
            var requestsCol = new TrainingsRequestsCollection();
            var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            if (request == null) return RedirectToAction("TrainingsRequests");
            if (request.TrainingsSchedules == null)
                return RedirectToAction("TrainingsRequestEdit", new {idTrainingsRequest});
            return View(request);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestDetailsPartal(int idTrainingsRequest)
        {
            var requestsCol = new CRM.Database.Model.TrainingsRequestsCollection();
            var request = (CRM.Database.Model.TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            return PartialView(request);
        }

        /// <summary>
        /// Редактирование заявки - определяет тип заявки и перенаправляет на соотвествующее действие. Или обратно на список заявок.
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestEdit(int idTrainingsRequest)
        {
            var requestsCol = new TrainingsRequestsCollection();
            var coursesCol = new TrainingsCoursesCollection();
            var schedulesCol = new TrainingsSchedulesCollection();

            var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            if (request == null)
                return RedirectToAction("TrainingsRequests");

            //Если заявка плановая
            //Редактирование плановой заявки
            if (request.TrainingsSchedules != null)
                if (request.TrainingsSchedules.TrainingsCourses != null)
                    if (request.TrainingsSchedules.TrainingCoursesTypes != null)
                        if (request.TrainingsSchedules.TrainingCoursesTypes.IdTrainingCoursesType == 1)
                            return RedirectToAction("TrainingsPlannedRequestEdit", new { IdTrainingsRequest = idTrainingsRequest });

            //Если заявка на выездной курс
            //Редактирование выездной заявки, не привязанной к расписанию
            if (request.IdTrainingsSchedule == null)
            {
                if (request.IdCustomer > 0)
                {
                    if (request.IdTrainingsCourse > 0)
                    {
                        var course = (TrainingsCourses)coursesCol.GetItemById(request.IdTrainingsCourse);
                        //var course = DB.GetTrainingsCoursebyId(request.IdTrainingsCourse);
                        if (course != null)
                        {
                            if (course.IsRemote)
                            {
                                return RedirectToAction("TrainingsRemoteRequestEdit", new { IdTrainingsRequest = idTrainingsRequest });
                            }
                        }
                    }
                }
            }

            //Редактирование выездной заявки, уже привязанной к расписанию (редактирование второй и более раз)
            if (request.IdTrainingsSchedule > 0)
            {
                if (request.IdCustomer > 0)
                {
                    if (request.IdTrainingsCourse > 0)
                    {
                        if (request.IdTrainingsSchedule != null)
                        {
                            var schedule = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById((int)request.IdTrainingsSchedule);
                            //var schedule = DB.GetTrainingsSchedulebyId((int)request.IdTrainingsSchedule);
                            if (schedule != null)
                            {
                                if (schedule.IdTrainingCoursesType == 2)
                                    return RedirectToAction("TrainingsRemoteRequestEditSecondTime", new { IdTrainingsRequest = idTrainingsRequest });
                            }
                        }
                        //var course = DB.GetTrainingsCoursebyId(request.IdTrainingsCourse);
                        //if (course != null)
                        //{
                        //    if (course.TrainingCoursesTypes != null)
                        //    {
                        //        if (course.IdTrainingCoursesType == 2)
                        //            return RedirectToAction("TrainingsRemoteRequestEditSecondTime", new { IdTrainingsRequest = idTrainingsRequest });
                        //    }
                        //}
                    }
                }
            }

            //Если вебинар
            //Редактирование заявки на вебинар
            if (request.TrainingsSchedules != null)
                if (request.TrainingsSchedules.TrainingsCourses != null)
                    if (request.TrainingsSchedules.TrainingCoursesTypes != null)
                        if (request.TrainingsSchedules.TrainingCoursesTypes.IdTrainingCoursesType == 3)
                            return RedirectToAction("TrainingsWebinarRequestEdit", new { IdTrainingsRequest = idTrainingsRequest });

            return RedirectToAction("TrainingsRequests");
        }

        #endregion

        #region PlannedRequest - moved

        //Плановая заявка

        /// <summary>
        /// создание новой плановой заявки
        /// </summary>
        /// <param name="scheduleId"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public ActionResult TrainingsPlannedRequestCreate(int scheduleId, int customerId)
        {
            var contactsCol = new CRM.Database.Model.ContactsCollection();
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();

            var requestExt = new CRM.Database.Model.TrainingsRequestsExt();
            requestExt.Request.IdCustomer = customerId;
            requestExt.Request.IdTrainingsSchedule = scheduleId;

            //заполнение начальными значениями юр лиц и котнактов
            var legalEntitiesList = leCol.GetFullDefinedLegalEntitiesByCustomerId(customerId);
            //var legalEntitiesList = DB.GetFullDefinedLegalEntitiesByCustomerId(customerId);
            if (legalEntitiesList.Count > 0)
                if (legalEntitiesList.FirstOrDefault()!=null)
                {
                    requestExt.IdLegalEntity = legalEntitiesList.First().IdLegalEntity;
                    var contactsList = contactsCol.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity);
                    //var contactsList = DB.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity);
                    if (contactsList.Count > 0)
                        if (contactsList.FirstOrDefault() != null)
                            requestExt.IdContact = contactsList.First().IdContact;
                }

            //var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
            //if (customer != null)
            //{
            //    if (customer.LegalEntities != null)
            //    {
            //        var entity = customer.LegalEntities.FirstOrDefault();
            //        if (entity != null)
            //        {
            //            requestExt.Request.IdLegalEntity = entity.IdLegalEntity;
            //            requestExt.Request.IdCustomer = customerId;
            //        }
            //    }
            //    if(customer.Contacts != null)
            //    {
            //        var contact = customer.Contacts.FirstOrDefault();
            //        if(contact!=null)
            //        {
            //            requestExt.Request.IdContact = contact.IdContact;
            //        }
            //    }
            //}

            var key = DB.TrainingsRequestsExtDic.Count;
            //requestExt.Request.IdTrainingsRequest = key;
            requestExt.Key = key;
            DB.TrainingsRequestsExtDic.Add(key,requestExt);
            
            return View(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlannedRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsRequestsExt requestsExtNew)
        {
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var contactsCol = new CRM.Database.Model.ContactsCollection();
            var schedulesCol = new TrainingsSchedulesCollection();

            requestsExtNew.Fill();
            //DB.FillTrainingsRequestExt(requestsExtNew);
            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.RequestDate = DateTime.Now;
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.IdTrainingsRequestsStatus = 1;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((CRM.Database.Model.LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;
            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((CRM.Database.Model.Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;

            //получить Id курса из расписания
            if(resultRequestExt.Request.IdTrainingsSchedule != null)
                if(resultRequestExt.Request.IdTrainingsSchedule > 0)
                {
                    var schedule = (TrainingsSchedules)schedulesCol.GetItemById((int)resultRequestExt.Request.IdTrainingsSchedule);
                    if (schedule != null)
                        resultRequestExt.Request.IdTrainingsCourse = schedule.IdTrainingsCource;
                }
            resultRequestExt.Fill();

            var result = resultRequestExt.SaveToDb(Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsExtInsert(resultRequestExt);
            
            //return RedirectToAction("TrainingsRequests");
            return RedirectToAction("Details", "Customers", new {id = resultRequestExt.Request.IdCustomer});
        }

        public ActionResult TrainingsPlannedRequestSchedulePartial(int key)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();

            var requestExt = DB.TrainingsRequestsExtDic[key];
            var scheduleId = requestExt.Request.IdTrainingsSchedule;
            if (scheduleId != null)
            {
                var schedule = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById((int)scheduleId);
                //var schedule = DB.GetTrainingsSchedulebyId((int)scheduleId);
                return PartialView(schedule);
            }
            return RedirectToAction("TrainingsRequests");
        }

        /// <summary>
        /// Редактирование плановой заявки
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsPlannedRequestEdit(int idTrainingsRequest)
        {
            var requestCol = new CRM.Database.Model.TrainingsRequestsCollection();

            var requestItem = (CRM.Database.Model.TrainingsRequests)requestCol.GetItemById(idTrainingsRequest);
            //var requestItem = DB.GetTrainingsRequestesById(idTrainingsRequest);
            if (requestItem != null)
            {
                var requestExt = new CRM.Database.Model.TrainingsRequestsExt {Request = requestItem};

                foreach (var item in requestExt.Request.TrainingsParticipants)
                {
                    var participant = new CRM.Database.Model.TrainingsParticipants
                                          {
                                              IdTrainingsParticipant = item.IdTrainingsParticipant,
                                              IdTrainingsParticipantsStatus = item.IdTrainingsParticipantsStatus,
                                              IdTrainingsRequest = item.IdTrainingsRequest,
                                              IdUser = item.IdUser,
                                              ParticipantName = item.ParticipantName,
                                              ParticipantPosition = item.ParticipantPosition
                                          };
                    requestExt.ParticipantsList.Add(participant);
                }

                if (requestExt.Request.IdLegalEntity != null)
                    requestExt.IdLegalEntity = (int) requestExt.Request.IdLegalEntity;
                if (requestExt.Request.IdContact != null) 
                    requestExt.IdContact = (int) requestExt.Request.IdContact;

                ////получение IdLegalEntity, если оно было введено руками
                //if (!(requestExt.Request.IdLegalEntity > 0))
                //{
                //    if (requestExt.Request.IdCustomer != null)
                //    {
                //        var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
                //        if(customer != null)
                //        {
                //            var legalEntity = DB.GetLegalEntityByName(requestExt.Request.Company, customer);
                //            if (legalEntity != null)
                //            {
                //                requestExt.Request.IdLegalEntity = legalEntity.IdLegalEntity;
                //                requestExt.IdLegalEntity = legalEntity.IdLegalEntity;
                //            }
                //        }
                //    }
                //}
                //if(requestExt.Request.IdLegalEntity == null)
                //{
                //    if (requestExt.Request.IdCustomer != null)
                //    {
                //        var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
                //        if(customer!=null)
                //        {
                //            if (customer.LegalEntities != null)
                //            {
                //                var entity = customer.LegalEntities.FirstOrDefault();
                //                if (entity != null)
                //                    requestExt.Request.IdLegalEntity = entity.IdLegalEntity;
                //            }
                //        }
                //    }
                //}

                var key = DB.TrainingsRequestsExtDic.Count;
                requestExt.Key = key;
                DB.TrainingsRequestsExtDic.Add(key, requestExt);
                return View(requestExt);
            }
            return RedirectToAction("TrainingsRequests");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlannedRequestEdit([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsRequestsExt requestsExtNew)
        {
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var contactsCol = new CRM.Database.Model.ContactsCollection();
            
            requestsExtNew.Fill();
            //DB.FillTrainingsRequestExt(requestsExtNew);
            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.RequestDate = requestsExtNew.Request.RequestDate;
            resultRequestExt.Request.IdTrainingsRequestsStatus = requestsExtNew.Request.IdTrainingsRequestsStatus;
            resultRequestExt.Request.IdTrainingsSchedule = requestsExtNew.Request.IdTrainingsSchedule;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((CRM.Database.Model.LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;
            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((CRM.Database.Model.Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;

            var result =  resultRequestExt.UpdateToDb(Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsExtUpdate(resultRequestExt);)
            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest = resultRequestExt.Request.IdTrainingsRequest });
        }

        #endregion

        #region RemoteRequest - moved

        //Удаленная заявка

        /// <summary>
        /// Новая заявка на выездной курс
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public ActionResult TrainingsRemoteRequestCreate(int courseId, int customerId)
        {
            var leCol = new LegalEntitiesCollection();
            var contactsCol = new ContactsCollection();

            var requestExt = new TrainingsRequestsExt();
            requestExt.Request.IdCustomer = customerId;
            requestExt.Request.IdTrainingsCourse = courseId;

            //заполнение начальными значениями юр лиц и котнактов
            var legalEntitiesList = leCol.GetFullDefinedLegalEntitiesByCustomerId(customerId);
            if (legalEntitiesList.Count > 0)
                if (legalEntitiesList.FirstOrDefault() != null)
                {
                    requestExt.IdLegalEntity = legalEntitiesList.First().IdLegalEntity;
                    var contactsList = contactsCol.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity);
                    if (contactsList.Count > 0)
                        if (contactsList.FirstOrDefault() != null)
                            requestExt.IdContact = contactsList.First().IdContact;
                }

            //var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
            //if (customer != null)
            //{
            //    if (customer.LegalEntities != null)
            //    {
            //        var entity = customer.LegalEntities.FirstOrDefault();
            //        if (entity != null)
            //        {
            //            requestExt.Request.IdLegalEntity = entity.IdLegalEntity;
            //            requestExt.Request.IdCustomer = customerId;
            //        }
            //    }
            //    if (customer.Contacts != null)
            //    {
            //        var contact = customer.Contacts.FirstOrDefault();
            //        if (contact != null)
            //        {
            //            requestExt.Request.IdContact = contact.IdContact;
            //        }
            //    }
            //}
                

            var key = DB.TrainingsRequestsExtDic.Count;
            requestExt.Key = key;
            DB.TrainingsRequestsExtDic.Add(key, requestExt);

            return View(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsRemoteRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequestsExt requestsExtNew)
        {
            var leCol = new LegalEntitiesCollection();
            var contactsCol = new ContactsCollection();
            
            requestsExtNew.Fill();

            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.RequestDate = DateTime.Now;
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.IdTrainingsRequestsStatus = 1;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.FirstDate = requestsExtNew.Request.FirstDate;
            resultRequestExt.Request.LastDate = requestsExtNew.Request.LastDate;
            resultRequestExt.Request.Reason = requestsExtNew.Request.Reason;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;
            resultRequestExt.Request.IdTrainingsAuditorium = requestsExtNew.IdTrainingsAuditorium;
            resultRequestExt.Request.PredictParticipantsCount = requestsExtNew.Request.PredictParticipantsCount;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;

            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;

            var result = resultRequestExt.SaveToDb(Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsExtInsert(resultRequestExt);

            //return RedirectToAction("TrainingsRequests");)
            return RedirectToAction("Details", "Customers", new { id = resultRequestExt.Request.IdCustomer });
        }

        public ActionResult TrainingsRemoteRequestSchedulePartial(int key)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();
            var requestExt = DB.TrainingsRequestsExtDic[key];
            var scheduleId = requestExt.Request.IdTrainingsSchedule;
            if (scheduleId != null)
            {
                var schedule = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById((int)scheduleId);
                //var schedule = DB.GetTrainingsSchedulebyId((int)scheduleId);
                return PartialView(schedule);
            }
            return RedirectToAction("TrainingsRequests");
        }

        /// <summary>
        /// Редактирование удаленной заявки
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRemoteRequestEdit(int idTrainingsRequest)
        {
            var requestCol = new TrainingsRequestsCollection();
            var trainersCol = new TrainingsTrainersCollection();

            var requestItem = (TrainingsRequests)requestCol.GetItemById(idTrainingsRequest);
            if (requestItem != null)
            {
                var requestExt = new TrainingsRequestsExt {Request = requestItem};
                if (requestItem.IdTrainingsAuditorium != null)
                    requestExt.IdTrainingsAuditorium = (int) requestItem.IdTrainingsAuditorium;

                requestExt.IdTrainingsCourse = requestExt.Request.IdTrainingsCourse;
                
                foreach (var item in requestExt.Request.TrainingsParticipants)
                {
                    var participant = new TrainingsParticipants
                                          {
                                              IdTrainingsParticipant = item.IdTrainingsParticipant,
                                              IdTrainingsParticipantsStatus = item.IdTrainingsParticipantsStatus,
                                              IdTrainingsRequest = item.IdTrainingsRequest,
                                              IdUser = item.IdUser,
                                              ParticipantName = item.ParticipantName,
                                              ParticipantPosition = item.ParticipantPosition
                                          };
                    requestExt.ParticipantsList.Add(participant);
                }

                //if (requestExt.Request.IdCustomer != null)
                //{
                //    var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
                //    if (customer != null)
                //        if (customer.Name != null)
                //            requestExt.Request.Company = customer.Name;
                //}
                ////получение IdLegalEntity, если оно было введено руками
                //if (!(requestExt.Request.IdLegalEntity > 0))
                //{
                //    if (requestExt.Request.IdCustomer != null)
                //    {
                //        var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
                //        if (customer != null)
                //        {
                //            var legalEntity = DB.GetLegalEntityByName(requestExt.Request.Company, customer);
                //            if (legalEntity != null)
                //                requestExt.Request.IdLegalEntity = legalEntity.IdLegalEntity;
                //        }
                //    }
                //}

                //получение списка тренеров
                var trainersList = trainersCol.GetTrainersListByCourseId(requestExt.Request.IdTrainingsCourse);
                if (trainersList != null)
                    if (trainersList.Count > 0)
                        requestExt.IdTrainingsTrainer = trainersList.First().IdTrainingsTrainer;

                //requestExt.ScheduleDate = new DateTime(1900, 1, 1);
                requestExt.ScheduleDate = DateTime.Now;

                if (requestExt.Request.IdLegalEntity != null)
                    requestExt.IdLegalEntity = (int)requestExt.Request.IdLegalEntity;
                if (requestExt.Request.IdContact != null)
                    requestExt.IdContact = (int)requestExt.Request.IdContact;

                var key = DB.TrainingsRequestsExtDic.Count;
                requestExt.Key = key;
                DB.TrainingsRequestsExtDic.Add(key, requestExt);
                return View(requestExt);
            }
            return RedirectToAction("TrainingsRequests");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsRemoteRequestEdit([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequestsExt requestsExtNew)
        {
            var statusesCol = new TrainingCoursesStatusesCollection();
            var placesCol = new TrainingsPlacesCollection();
            var schedulesCol = new TrainingsSchedulesCollection();
            var requestsCol = new TrainingsRequestsCollection();
            var leCol = new LegalEntitiesCollection();
            var contactsCol = new ContactsCollection();
            var profineRegionsCol = new profineRegionsCollection();

            requestsExtNew.Fill();
            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.RequestDate = requestsExtNew.Request.RequestDate;
            resultRequestExt.Request.IdTrainingsRequestsStatus = 3;
            resultRequestExt.Request.IdTrainingsSchedule = requestsExtNew.Request.IdTrainingsSchedule;
            resultRequestExt.Request.FirstDate = requestsExtNew.Request.FirstDate;
            resultRequestExt.Request.LastDate = requestsExtNew.Request.LastDate;
            resultRequestExt.Request.Reason = requestsExtNew.Request.Reason;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;
            resultRequestExt.Request.IdTrainingsCourse = requestsExtNew.IdTrainingsCourse;


            resultRequestExt.Request.PredictParticipantsCount = requestsExtNew.Request.PredictParticipantsCount;
            resultRequestExt.Request.IdTrainingsAuditorium = requestsExtNew.IdTrainingsAuditorium;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;

            resultRequestExt.UpdateToDb(Request.LogonUserIdentity.Name);
            var scheduleNew = new TrainingsSchedules();
            var requestEdit = (TrainingsRequests)requestsCol.GetItemById(resultRequestExt.Request.IdTrainingsRequest);

            //коллекция статусов
            if (requestEdit != null)
            {
                scheduleNew.PlannedDate = requestsExtNew.ScheduleDate;
                scheduleNew.IdTrainingsTrainer = requestsExtNew.IdTrainingsTrainer;
                scheduleNew.IdTrainingsCource = requestEdit.IdTrainingsCourse;
                scheduleNew.IdTrainingCoursesStatus = statusesCol.GetStatusIdByDate(scheduleNew.PlannedDate);
                if (scheduleNew.IdTrainingsPlace < 1)
                    //scheduleNew.IdTrainingsPlace = placesCol.TrainingsPlacesActiveList.First().IdTrainingsPlace;
                {
                    var place = placesCol.GetPlacesListByCourseId(scheduleNew.IdTrainingsCource).FirstOrDefault();
                    if (place != null)
                        scheduleNew.IdTrainingsPlace = place.IdTrainingsPlace;
                }
                scheduleNew.IdTrainingCoursesType = 2;
                scheduleNew.IdProfineRegion = 20; //не определен
                scheduleNew.IdTrainingsAuditorium = requestsExtNew.IdTrainingsAuditorium;
                scheduleNew.IdTrainingsCity = requestsExtNew.IdTrainingsCity;
                schedulesCol.Add(scheduleNew, Request.LogonUserIdentity.Name);
                if(scheduleNew.IdTrainingsSchedule > 0)
                {
                    resultRequestExt.Request.IdTrainingsSchedule = scheduleNew.IdTrainingsSchedule;
                }
            }

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;
            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;
            bool result = resultRequestExt.UpdateToDb(Request.LogonUserIdentity.Name);
            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest = resultRequestExt.Request.IdTrainingsRequest });
        }

        /// <summary>
        /// Редактирование выездной заявки, уже привязанной к расписанию
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRemoteRequestEditSecondTime(int idTrainingsRequest)
        {
            var requestsCol = new TrainingsRequestsCollection();

            var requestItem = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            if (requestItem != null)
            {
                var requestExt = new TrainingsRequestsExt {Request = requestItem};
                if (requestItem.IdTrainingsAuditorium != null)
                    requestExt.IdTrainingsAuditorium = (int)requestItem.IdTrainingsAuditorium;

                foreach (var item in requestExt.Request.TrainingsParticipants)
                {
                    var participant = new TrainingsParticipants
                                          {
                                              IdTrainingsParticipant = item.IdTrainingsParticipant,
                                              IdTrainingsParticipantsStatus = item.IdTrainingsParticipantsStatus,
                                              IdTrainingsRequest = item.IdTrainingsRequest,
                                              IdUser = item.IdUser,
                                              ParticipantName = item.ParticipantName,
                                              ParticipantPosition = item.ParticipantPosition
                                          };
                    requestExt.ParticipantsList.Add(participant);
                }

                ////получение IdLegalEntity, если оно было введено руками
                //if (!(requestExt.Request.IdLegalEntity > 0))
                //{
                //    if (requestExt.Request.IdCustomer != null)
                //    {
                //        var customer = DB.GetCustomerById((int)requestExt.Request.IdCustomer);
                //        if (customer != null)
                //        {
                //            var legalEntity = DB.GetLegalEntityByName(requestExt.Request.Company, customer);
                //            if (legalEntity != null)
                //                requestExt.Request.IdLegalEntity = legalEntity.IdLegalEntity;
                //        }
                //    }
                //}

                if (requestExt.Request.IdLegalEntity != null)
                    requestExt.IdLegalEntity = (int)requestExt.Request.IdLegalEntity;
                if (requestExt.Request.IdContact != null)
                    requestExt.IdContact = (int)requestExt.Request.IdContact;

                var key = DB.TrainingsRequestsExtDic.Count;
                requestExt.Key = key;
                DB.TrainingsRequestsExtDic.Add(key, requestExt);
                return View(requestExt);
            }
            return RedirectToAction("TrainingsRequests");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsRemoteRequestEditSecondTime([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequestsExt requestsExtNew)
        {
            requestsExtNew.Fill();

            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.RequestDate = requestsExtNew.Request.RequestDate;
            resultRequestExt.Request.IdTrainingsRequestsStatus = requestsExtNew.Request.IdTrainingsRequestsStatus;
            resultRequestExt.Request.IdTrainingsSchedule = requestsExtNew.Request.IdTrainingsSchedule;
            resultRequestExt.Request.FirstDate = requestsExtNew.Request.FirstDate;
            resultRequestExt.Request.LastDate = requestsExtNew.Request.LastDate;
            resultRequestExt.Request.Reason = requestsExtNew.Request.Reason;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;

            resultRequestExt.Request.PredictParticipantsCount = requestsExtNew.Request.PredictParticipantsCount;
            resultRequestExt.Request.IdTrainingsAuditorium = requestsExtNew.IdTrainingsAuditorium;

            resultRequestExt.UpdateToDb(Request.LogonUserIdentity.Name);

            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest = resultRequestExt.Request.IdTrainingsRequest });
        }

        //Callbacks для редактирования удаленной заявки в первый раз

        public ActionResult TrainingsRemoteRequestEditCoursesPartial()
        {
            return PartialView();
        }

        public ActionResult TrainingsRemoteRequestEditAuditoriumsPartial(int key)
        {
            var idCourse = (Request.Params["IDCOURSE"] != null) ? int.Parse(Request.Params["IDCOURSE"]) : -1;
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.IdTrainingsCourse = idCourse;
            return PartialView(requestExt);
        }

        public ActionResult TrainingsRemoteRequestEditTrainersPartial(int key)
        {
            var idCourse = (Request.Params["IDCOURSE"] != null) ? int.Parse(Request.Params["IDCOURSE"]) : -1;
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.IdTrainingsCourse = idCourse;
            return PartialView(requestExt);
        }

        public ActionResult TrainingsRemoteRequestEditPlacesPartial(int key)
        {
            var idCourse = (Request.Params["IDCOURSE"] != null) ? int.Parse(Request.Params["IDCOURSE"]) : -1;
            var requestExt = DB.TrainingsRequestsExtDic[key];
            requestExt.IdTrainingsCourse = idCourse;
            return PartialView(requestExt);
        }

        #endregion

        #region webinar - moved

        //Вебинар

        /// <summary>
        /// Новый вебинар
        /// </summary>
        /// <param name="scheduleId"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public ActionResult TrainingsWebinarRequestCreate(int scheduleId, int customerId)
        {
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var contactsCol = new CRM.Database.Model.ContactsCollection();

            var requestExt = new CRM.Database.Model.TrainingsRequestsExt();
            requestExt.Request.IdCustomer = customerId;
            requestExt.Request.IdTrainingsSchedule = scheduleId;

            //заполнение начальными значениями юр лиц и котнактов
            var legalEntitiesList = leCol.GetFullDefinedLegalEntitiesByCustomerId(customerId);
            //var legalEntitiesList = DB.GetFullDefinedLegalEntitiesByCustomerId(customerId);
            if (legalEntitiesList.Count > 0)
                if (legalEntitiesList.FirstOrDefault() != null)
                {
                    requestExt.IdLegalEntity = legalEntitiesList.First().IdLegalEntity;
                    var contactsList = contactsCol.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity);
                    //var contactsList = DB.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity);
                    if (contactsList.Count > 0)
                        if (contactsList.FirstOrDefault() != null)
                            requestExt.IdContact = contactsList.First().IdContact;
                }

            var key = DB.TrainingsRequestsExtDic.Count;
            requestExt.Key = key;
            DB.TrainingsRequestsExtDic.Add(key, requestExt);
            return View(requestExt);

            //var request = new TrainingsRequests();
            //request.IdTrainingsSchedule = scheduleId;
            //request.IdCustomer = customerId;
            //var customer = DB.GetCustomerById((int)request.IdCustomer);
            //if (customer != null)
            //{
            //    if (customer.LegalEntities != null)
            //    {
            //        var entity = customer.LegalEntities.FirstOrDefault();
            //        if (entity != null)
            //        {
            //            request.IdLegalEntity = entity.IdLegalEntity;
            //            request.IdCustomer = customerId;
            //        }
            //    }
            //    if (customer.Contacts != null)
            //    {
            //        var contact = customer.Contacts.FirstOrDefault();
            //        if (contact != null)
            //        {
            //            request.IdContact = contact.IdContact;
            //        }
            //    }
            //}
            //return View(request);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsWebinarRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsRequestsExt requestsExtNew)
        {
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var contactsCol = new CRM.Database.Model.ContactsCollection();
            var schedulesCol = new TrainingsSchedulesCollection();

            requestsExtNew.Fill();
            //DB.FillTrainingsRequestExt(requestsExtNew);
            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.RequestDate = DateTime.Now;
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.IdTrainingsRequestsStatus = 1;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((CRM.Database.Model.LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;
            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((CRM.Database.Model.Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;

            //получить Id курса из расписания
            if (resultRequestExt.Request.IdTrainingsSchedule != null)
                if (resultRequestExt.Request.IdTrainingsSchedule > 0)
                {
                    var schedule = (TrainingsSchedules)schedulesCol.GetItemById((int)resultRequestExt.Request.IdTrainingsSchedule);
                    if (schedule != null)
                        resultRequestExt.Request.IdTrainingsCourse = schedule.IdTrainingsCource;
                }
            resultRequestExt.Fill();

            var result = resultRequestExt.SaveToDb(Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsExtInsert(resultRequestExt);
            //return RedirectToAction("TrainingsRequests");)
            return RedirectToAction("Details", "Customers", new { id = resultRequestExt.Request.IdCustomer });
            
            //DB.FillTrainingsRequest(requestNew);
            //requestNew.RequestDate = DateTime.Now;
            //requestNew.IdUser = Request.LogonUserIdentity.Name;
            //requestNew.IdTrainingsRequestsStatus = 1;
            //DB.TrainingsRequestsInsert(requestNew);
            //if (requestNew.IdLegalEntity != null)
            //    requestNew.Company = requestNew.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestNew.IdLegalEntity).Name : requestNew.Company;
            //if (requestNew.IdContact != null)
            //    requestNew.ContactName = requestNew.IdContact > 0 ? DB.GetContactById((int)requestNew.IdContact).Name : requestNew.ContactName;
            //return RedirectToAction("TrainingsRequests");
        }

        public ActionResult TrainingsWebinarRequestSchedulePartial(int key)
        {
            var schedulesCol = new CRM.Database.Model.TrainingsSchedulesCollection();

            var requestExt = DB.TrainingsRequestsExtDic[key];
            var scheduleId = requestExt.Request.IdTrainingsSchedule;
            if (scheduleId != null)
            {
                var schedule = (CRM.Database.Model.TrainingsSchedules)schedulesCol.GetItemById((int)scheduleId);
                //var schedule = DB.GetTrainingsSchedulebyId((int)scheduleId);
                return PartialView(schedule);
            }
            return RedirectToAction("TrainingsRequests");
        }

        /// <summary>
        /// Редактирование заявки на вбинар
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsWebinarRequestEdit(int idTrainingsRequest)
        {
            var requestsCol = new CRM.Database.Model.TrainingsRequestsCollection();

            var requestItem = (CRM.Database.Model.TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            //var requestItem = DB.GetTrainingsRequestesById(idTrainingsRequest);
            if (requestItem != null)
            {
                var requestExt = new CRM.Database.Model.TrainingsRequestsExt {Request = requestItem};
                if (requestExt.Request.IdLegalEntity != null)
                    requestExt.IdLegalEntity = (int)requestExt.Request.IdLegalEntity;
                if (requestExt.Request.IdContact != null)
                    requestExt.IdContact = (int)requestExt.Request.IdContact;

                var key = DB.TrainingsRequestsExtDic.Count;
                requestExt.Key = key;
                DB.TrainingsRequestsExtDic.Add(key, requestExt);
                return View(requestExt);
            }
            return RedirectToAction("TrainingsRequests");
            
            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            //if(request!=null)
            //{
            //    if(request.IdCustomer != null)
            //    {
            //        //получение IdLegalEntity, если оно было введено руками
            //        if (!(request.IdLegalEntity > 0))
            //        {
            //            var customer = DB.GetCustomerById((int) request.IdCustomer);
            //            if (customer != null)
            //            {
            //                var legalEntity = DB.GetLegalEntityByName(request.Company, customer);
            //                if (legalEntity != null)
            //                    request.IdLegalEntity = legalEntity.IdLegalEntity;
            //            }
            //        }
            //    }
            //    return View(request);
            //}
            //return RedirectToAction("TrainingsRequests");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsWebinarRequestEdit([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsRequestsExt requestsExtNew)
        {
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var contactsCol = new CRM.Database.Model.ContactsCollection();

            requestsExtNew.Fill();
            //DB.FillTrainingsRequestExt(requestsExtNew);
            var resultRequestExt = DB.TrainingsRequestsExtDic[(int)requestsExtNew.Key];
            resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
            resultRequestExt.Request.Company = requestsExtNew.Request.Company;
            resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
            resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
            resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
            resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
            resultRequestExt.Request.RequestDate = requestsExtNew.Request.RequestDate;
            resultRequestExt.Request.IdTrainingsRequestsStatus = requestsExtNew.Request.IdTrainingsRequestsStatus;
            resultRequestExt.Request.IdTrainingsSchedule = requestsExtNew.Request.IdTrainingsSchedule;
            resultRequestExt.Request.IdContact = requestsExtNew.IdContact;
            resultRequestExt.Request.IdLegalEntity = requestsExtNew.IdLegalEntity;

            if (requestsExtNew.Request.IdLegalEntity != null)
                resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? ((CRM.Database.Model.LegalEntities)leCol.GetItemById((int)requestsExtNew.Request.IdLegalEntity)).Name : requestsExtNew.Request.Company;
                //resultRequestExt.Request.Company = requestsExtNew.Request.IdLegalEntity > 0 ? DB.GetLegalEntityById((int)requestsExtNew.Request.IdLegalEntity).Name : requestsExtNew.Request.Company;
            if (requestsExtNew.Request.IdContact != null)
                resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? ((CRM.Database.Model.Contacts)contactsCol.GetItemById((int)requestsExtNew.Request.IdContact)).Name : requestsExtNew.Request.ContactName;
                //resultRequestExt.Request.ContactName = requestsExtNew.Request.IdContact > 0 ? DB.GetContactById((int)requestsExtNew.Request.IdContact).Name : requestsExtNew.Request.ContactName;

            var result = resultRequestExt.SaveToDb(Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsExtUpdate(resultRequestExt);
            //return RedirectToAction("TrainingsRequests");)
            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest = resultRequestExt.Request.IdTrainingsRequest });
        }

        #endregion

        #endregion

        #region TrainingsCities - moved

        [CheckAccessAttribute]
        public ActionResult TrainingsCities()
        {
            var citiesCol = new CRM.Database.Model.TrainingsCitiesCollection();
            return View(citiesCol.TrainingsCitiesList);
            //return View(DB.TrainingsCities);
        }

        public ActionResult TrainingsCitiesPartial()
        {
            var citiesCol = new CRM.Database.Model.TrainingsCitiesCollection();
            return PartialView("TrainingsCitiesPartial", citiesCol.TrainingsCitiesList);
            //return PartialView("TrainingsCitiesPartial", DB.TrainingsCities);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCitiesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCities trainingsCityItem)
        {
            var citiesCol = new CRM.Database.Model.TrainingsCitiesCollection();
            if (ModelState.IsValid)
            {
                citiesCol.Update(trainingsCityItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCitiesUpdate(trainingsCityItem);
            }
            return PartialView("TrainingsCitiesPartial", citiesCol.TrainingsCitiesList);
            //return PartialView("TrainingsCitiesPartial", DB.TrainingsCities);
        }

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TrainingsCitiesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCities trainingsCityItem)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        var citiesCol = new CRM.Database.Model.TrainingsCitiesCollection();
        //        citiesCol.Delete(trainingsCityItem);
        //        //DB.TrainingsCitiesDelete(trainingsCityItem);
        //    }
        //    return PartialView("TrainingsCitiesPartial", DB.TrainingsCities);
        //}

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsCitiesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsCities trainingsCityItem)
        {
            var citiesCol = new CRM.Database.Model.TrainingsCitiesCollection();
            if (ModelState.IsValid)
            {
                citiesCol.Add(trainingsCityItem, Request.LogonUserIdentity.Name);
                //DB.TrainingsCitiesInsert(trainingsCityItem);
            }
            return PartialView("TrainingsCitiesPartial", citiesCol.TrainingsCitiesList);
            //return PartialView("TrainingsCitiesPartial", DB.TrainingsCities);
        }

        #endregion

        #region CustomerTraining - moved

        public ActionResult CustomerTraining(CRM.Database.Model.Customers currentCustomer)
        {
            return PartialView(currentCustomer);
        }

        public ActionResult CustomerTrainingEdit(int customerId)
        {
            var customersCol = new CRM.Database.Model.CustomersCollection();
            var customer = (CRM.Database.Model.Customers)customersCol.GetItemById(customerId);
            return PartialView(customer);
            //return PartialView(DB.GetCustomerById(customerId));
        }

        public ActionResult CustomerTrainingRequestsPartial(int customerId)
        {
            return PartialView(customerId);
        }

        public ActionResult CustomerAuthorizationEdit(int customerId)
        {
            return PartialView(customerId);
        }

        public ActionResult CustomerAuthorizationEditPartial(int customerId)
        {
            return PartialView(customerId);
        }

        [HttpPost, ValidateInput(true)]
        public ActionResult CustomerAuthorizationEditPartialEdit([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.Contacts contact, int customerId)
        {
            if (!contact.IsLoginNameValid)
            {
                ModelState.AddModelError("LoginName", Resourses.Resourses.TrainingsLoginValidationError);
                ViewData["EditError"] = Resourses.Resourses.TrainingsLoginValidationError;
            }
            if(ModelState.IsValid)
            {
                contact.UpdateLoginAndPassword(Request.LogonUserIdentity.Name);
            }
            return PartialView("CustomerAuthorizationEditPartial", customerId);
        }

        #endregion

        #region SendMail - moved

        #region Test sending - moved

        [CheckAccessAttribute]
        public ActionResult SendMail()
        {
            var log = TempData["log"] as string;
            if (string.IsNullOrEmpty(log)) log = ""; 
            ViewData["log"] = log;
            var message = new CRM.Database.Model.Rubrics();
            return View(message);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult SendMail([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.Rubrics message)
        {
            var configurationsCol = new CRM.Database.Model.ConfigurationsCollection();
            //message.NameRu = To   
            //message.IdUser = Attachment 
            //message.DescriptionEn = Subject
            //message.DescriptionRu = Body
            if (String.IsNullOrEmpty(message.NameRu)) message.NameRu = "28katkow02@lnprof01.kbemos.ru";
            if (String.IsNullOrEmpty(message.DescriptionRu)) message.DescriptionRu = "Test body";
            if (String.IsNullOrEmpty(message.IdUser)) message.IdUser = configurationsCol.TrainingsAcceptenceMoscowFilePath;
            //if (String.IsNullOrEmpty(message.IdUser)) message.IdUser = Configurations.TrainingsAcceptenceMoscowFilePath;
            
            var paramsItem = new DocReport.DocReportParamsItem(DocBookmarks.CourseDate, DateTime.Now.ToString());
            var paramsItemList = new List<DocReport.DocReportParamsItem> {paramsItem};

            Utilites.DocReport.CreateDoc(configurationsCol.TrainingsAcceptenceMoscowFilePath,
                                            configurationsCol.TrainingsDocsTargetPath + "\\target.doc",
                                            paramsItemList
                                        );
            //Utilites.DocReport.CreateDoc(configurationsCol.TrainingsAcceptenceMoscowFilePath,
            //                                Configurations.TrainingsDocsTargetPath + "\\target.doc",
            //                                paramsItemList
            //                            );
            
            var log = Utilites.Mail.SendMail(
                                                message.NameRu, //to
                                                configurationsCol.TrainingsDefaultMAILFROMString, //from
                                                message.DescriptionEn, //subject
                                                message.DescriptionRu, //body
                                                message.IdUser, //attachment
                                                configurationsCol.MailServerIp, //ip
                                                configurationsCol.MailServerPort //port
                                             );
            //var log = Utilites.Mail.SendMail(
            //                                    message.NameRu, //to
            //                                    DB.GetDefaultMailFromStringTrainings(), //from
            //                                    message.DescriptionEn, //subject
            //                                    message.DescriptionRu, //body
            //                                    message.IdUser, //attachment
            //                                    DB.GetMailServerIp(), //ip
            //                                    DB.GetMailServerPort() //port
            //                                 );

            if (String.IsNullOrEmpty(log)) log = "OK";
            TempData["log"] = log;
            
            return RedirectToAction("SendMail");
        }

        #endregion

        /// <summary>
        /// Отправить уведомление о получении заявки контактному лицу
        /// типы заявок: плановая
        /// получатели: контактное лицо
        /// шаблон: 
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestSendNewMail(int idTrainingsRequest)
        {

            var confCol = new ConfigurationsCollection();
            var requestsCol = new TrainingsRequestsCollection();

            //остается вызов из DB
            var paramsList = DB.GetDocReportParamsByRequestId(idTrainingsRequest);
            if (paramsList != null)
            {
                var targetFilePath = confCol.TrainingsDocsTargetPath + "\\" + "new" + idTrainingsRequest;
                var sourceFilePath = confCol.TrainingsNewRequestFilePath;
                DocReport.CreateDoc(sourceFilePath, targetFilePath, paramsList);

                var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
                //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
                if (request != null)
                {
                    if(request.IsPlanned)
                    {
                        var log = DB.TrainingsSendNewMail(request);
                        //var log = request.SendNewMail();)
                        if (string.IsNullOrEmpty(log))
                        {
                            request.DateOfRegisterMail = DateTime.Now;
                            requestsCol.Update(request, Request.LogonUserIdentity.Name);
                            //DB.TrainingsRequestsUpdate(request);
                        }
                    }
                }
            }
            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest });
        }

        /// <summary>
        /// Отправляет предложение клиенту для выездных курсов или запрос менеджеру для плановых
        /// Получатели: 
        /// для выездных курсов: контактное лицо и менеджер
        /// для плановых: только менеджер
        /// шаблоны: выездной - confirmation_remote.doc
        /// плановый - 
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestSendConfirmationMail(int idTrainingsRequest)
        {
            var confCol = new ConfigurationsCollection();
            var requestsCol = new TrainingsRequestsCollection();
            var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);

            //вызов остается из DB
            //получение набора закладок из заявки
            var paramsList = DB.GetDocReportParamsByRequestId(idTrainingsRequest);
            if (paramsList == null) return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});

            //создание заполненного файла для вложения в письмо
            var targetFilePath = confCol.TrainingsDocsTargetPath + "\\confirmation" + idTrainingsRequest.ToString();

            var sourceFilePath = "";
            if(request.IsRemote)
                sourceFilePath = confCol.TrainingsConfirmationRemoteFilePath;
            if(request.IsPlanned)
                sourceFilePath = confCol.TrainingsConfirmationPlannedFilePath;
            
            DocReport.CreateDoc(sourceFilePath, targetFilePath, paramsList);

            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            if (request == null) return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});

            //отправка письма с вложением
            var subject = "";
            if (request.IsRemote) subject = "Предложение на выездной курс";
            if (request.IsPlanned) subject = "Запрос на плановые курс";
            var log = DB.TrainingsSendConfirmationMail(request, subject);
            //var log = request.SendConfirmationMail();
            if (!string.IsNullOrEmpty(log))
                return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});
            
            request.DateOfManagerMail = DateTime.Now;
            requestsCol.Update(request, Request.LogonUserIdentity.Name);
            //DB.TrainingsRequestsUpdate(request);
            
            return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});
        }

        /// <summary>
        /// Отправляет приглашение (подтверждение участия) на выездной курс контактному лицу
        /// Или на плановые курс контактному лицу с выбором шаблона отправки с катрой проезда
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestSendAcceptanceMail(int idTrainingsRequest)
        {
            var confCol = new ConfigurationsCollection();
            var requestsCol = new TrainingsRequestsCollection();
            var request = (TrainingsRequests) requestsCol.GetItemById(idTrainingsRequest);
            if (request == null) return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});

            //остается вызов из DB
            var paramsList = DB.GetDocReportParamsByRequestId(idTrainingsRequest);
            if (paramsList == null) return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});
            var targetFilePath = confCol.TrainingsDocsTargetPath + "\\acceptance" + idTrainingsRequest.ToString();
            
            var sourceFilePath = "";
            
            //if (request.IsRemote)
                //sourceFilePath = confCol.TrainingsAcceptanceRemoteFilePath;
            //if (request.IsPlanned)
                sourceFilePath = confCol.GetTrainingsAcceptanceFilePathByRequestId(idTrainingsRequest);
            
            DocReport.CreateDoc(sourceFilePath, targetFilePath, paramsList);

            //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
            var subject = "Приглашение";
            var log = DB.TrainingsSendAcceptanceMail(request, subject);
            //var log = request.SendAcceptanceMail();
            if (string.IsNullOrEmpty(log))
            {
                request.DateOfAcceptMail = DateTime.Now;
                requestsCol.Update(request, Request.LogonUserIdentity.Name);
                //DB.TrainingsRequestsUpdate(request);
            }
            return RedirectToAction("TrainingsRequestDetails", new {idTrainingsRequest});
        }

        /// <summary>
        /// Отправка отказа
        /// </summary>
        /// <param name="idTrainingsRequest"></param>
        /// <returns></returns>
        public ActionResult TrainingsRequestSendRefuseMail(int idTrainingsRequest)
        {
            var confCol = new ConfigurationsCollection();
            var requestsCol = new TrainingsRequestsCollection();
            var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
            if (request == null) return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest });
            //остается вызов из DB
            var paramsList = DB.GetDocReportParamsByRequestId(idTrainingsRequest);
            if (paramsList != null)
            {
                var targetFilePath = confCol.TrainingsDocsTargetPath + "\\refuse" + idTrainingsRequest;
                var sourceFilePath = "";
                if (request.IsPlanned)
                    sourceFilePath = confCol.TrainingsRefusePlannedFilePath;
                if(request.IsRemote)
                    sourceFilePath = confCol.TrainingsRefuseRemoteFilePath;

                DocReport.CreateDoc(sourceFilePath, targetFilePath, paramsList);

                //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);

                var log = DB.TrainingsSendRefuseMail(request);
                //var log = request.SendRefuseMail();
                if (string.IsNullOrEmpty(log))
                {
                    request.DateOfDeclineMail = DateTime.Now;
                    requestsCol.Update(request, Request.LogonUserIdentity.Name);
                    //DB.TrainingsRequestsUpdate(request);
                }
            }

            return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest });
        }

        #endregion

        #region TrainingsScheduler - moved

        [CheckAccessAttribute]
        public ActionResult Scheduler()
        {
            return View(SchedulerDataObject.TrainingsSchedulerObject);
        }

        public ActionResult SchedulerPartial()
        {
            return PartialView(SchedulerDataObject.TrainingsSchedulerObject);
        }

        #endregion

        #region TrainingsParticipants - moved

        /// <summary>
        /// Отображение списка всех участников расписания
        /// </summary>
        /// <param name="idTrainingsSchedule"></param>
        /// <returns></returns>
        public ActionResult TrainingsParticipantsList(int idTrainingsSchedule)
        {
            return View(idTrainingsSchedule);
        }

        public ActionResult TrainingsParticipantsListPartial(int idTrainingsSchedule)
        {
            return PartialView(idTrainingsSchedule);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsListPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsParticipants participantsUpdate, int idTrainingsSchedule)
        {
            var participantsCol = new CRM.Database.Model.TrainingsParticipantsCollection();
            if(participantsUpdate!= null)
            {
                participantsUpdate.Fill();
                participantsCol.Update(participantsUpdate, Request.LogonUserIdentity.Name);
                //participantsUpdate.IdUser = Request.LogonUserIdentity.Name;
                //DB.FillTrainingsParticipant(participantsUpdate);
                //DB.TrainingsParticipantsUpdate(participantsUpdate);
            }
            return PartialView("TrainingsParticipantsListPartial", idTrainingsSchedule);
        }

        #endregion

        #region TrainingsReports - moved

        [CheckAccessAttribute]
        public ActionResult RequestsReports()
        {
            var requestsCol = new TrainingsRequestsCollection();
            return View(requestsCol.TrainingsRequestsList);
        }

        public ActionResult RequestsReportsPartal()
        {
            var requestsCol = new TrainingsRequestsCollection();
            return PartialView(requestsCol.TrainingsRequestsList);
        }

        public ActionResult ExportTo()
        {
            var requestsCol = new TrainingsRequestsCollection();
            return GridViewExtension.ExportToXls(TrainingsRequestsExportGridViewSettings(), requestsCol.TrainingsRequestsList);
            //return GridViewExtension.ExportToXls(TrainingsRequestsExportGridViewSettings(), DB.TrainingsRequests);
        }

        static GridViewSettings TrainingsRequestsExportGridViewSettings()
        {
            //var schedulesCol = new TrainingsSchedulesCollection();
            //var statusesCol = new TrainingRequestsStatusesCollection();

            var settings = new GridViewSettings();
            settings.Name = "gdTrainingsRequest";
            settings.KeyFieldName = "IdTrainingsRequest";
            settings.CallbackRouteValues = new { Controller = "TC", Action = "RequestsReportsPartal" };
            settings.SettingsPager.PageSize = 20;
            settings.Settings.ShowFilterRow = true;
            //settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;

            //тип учебного курса 1)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsRequestsType;
                column.FieldName = "RequestType";
            });

            //рубрика 2)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsRubric;
                column.FieldName = "RubricName";
            });

            //регион 3)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.profineRegion;
                column.FieldName = "profineRegion";
            });

            //город 4) 
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCity;
                column.FieldName = "CityName";
            });

            //Название курса 5)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCourse;
                column.FieldName = "CourseNameExt";
            });

            //дата курса 5.5)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsScheduleDate;
                column.FieldName = "CourseDateExt";
                //column.ColumnType = MVCxGridViewColumnType.DateEdit;
            });

            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingsSchedule";
            //    column.Caption = Resourses.Resourses.TrainingsScheduleDate;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    column.PropertiesEdit.DisplayFormatString = "d";
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        comboBoxProperties.DisplayFormatString = "d";
            //        comboBoxProperties.DisplayFormatInEditMode = true;
            //        comboBoxProperties.DataSource = schedulesCol.TrainingsSchedulesList;
            //        comboBoxProperties.TextField = "PlannedDate";
            //        comboBoxProperties.ValueField = "IdTrainingsSchedule";
            //        comboBoxProperties.ValueType = typeof(int);
            //        comboBoxProperties.TextFormatString = "d";
            //    }
            //});

            //Кол-во дней 6)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsDuration;
                column.FieldName = "DurationExt";
            });

            //Кол-во участников (заявлено) 7)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCountRequested;
                column.FieldName = "ParticipantsCountRequested";
            });

            //Кол-во участников (фактическое) 8)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCountRequested;
                column.FieldName = "ParticipantsCountActual";
            });

            //компания (название клиента) 9)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCompany;
                column.FieldName = "CompanyExt";
            });

            //Стоимость курса 10)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCourseCost;
                column.FieldName = "CourseCost";
            });

            ////номер заявки
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsRequestNumber;
            //    column.FieldName = "IdTrainingsRequest";
                
            //});

            ////дата регистрицаа заявки
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsRegisterDate;
            //    column.FieldName = "RequestDate";
            //    column.ColumnType = MVCxGridViewColumnType.DateEdit;
            //});

            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingsSchedule";
            //    column.Caption = Resourses.Resourses.TrainingsCourse;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        comboBoxProperties.DataSource = DB.TrainingsSchedules;
            //        comboBoxProperties.TextField = "CourseName";
            //        comboBoxProperties.ValueField = "IdTrainingsSchedule";
            //        comboBoxProperties.ValueType = typeof(int);
            //    }
            //});

            ////контакстное лицо
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsContactName;
            //    column.FieldName = "ContactNameExt";
            //});

            ////контактный телефон
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsContactPhone;
            //    column.FieldName = "ContactPhoneExt";
            //});

            ////email
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsContactEmail;
            //    column.FieldName = "ContactEmailExt";
            //});

            ////комментарии
            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.Resourses.TrainingsComments;
            //    column.FieldName = "Comments";
            //});

            ////Статус заявки
            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingsRequestsStatus";
            //    column.Caption = Resourses.Resourses.TrainingRequestsStatus;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        comboBoxProperties.DataSource = statusesCol.TrainingRequestsStatusesActiveList;
            //        //comboBoxProperties.DataSource = DB.GetLocalizedTrainingRequestsStatusesNames(Thread.CurrentThread.CurrentCulture.ToString());
            //        comboBoxProperties.TextField = "LocalizedName";
            //        //comboBoxProperties.TextField = "LocaLizedString";
            //        comboBoxProperties.ValueField = "IdTrainingRequestsStatus";
            //        //comboBoxProperties.ValueField = "Id";
            //        comboBoxProperties.ValueType = typeof(int);
            //    }
            //});
            
            return settings;
        }

        /// <summary>
        /// Формирование отчета для печати 
        /// Регистрационная форма - coffee_brake_service.docx
        /// Регистрационная форма - registration_form.docx
        /// Регистрационная форма - members_list.docx
        /// </summary>
        /// <param name="idSchedule"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public FilePathResult TrainingsScheduleReportPrint(int idSchedule, string template)
        {
            //вспомогательные коллекции
            var confCol = new ConfigurationsCollection();
            var schedulesCol = new TrainingsSchedulesCollection();
            var resultFilePath = "";
            var templateFilePath = "";
            var tempFileName = Guid.NewGuid() +".docx";
            List<DocReport.DocReportTablesParams> listTablesParams = null;


            //формирование закладок для документа
            var paramsList = DB.GetDocReportParamsByScheduleId(idSchedule);

            //получение имен файлов (шаблона и результата)
            if(template == "coffee_brake_service.docx")
            {
                resultFilePath = confCol.TrainingsDocsTargetPath + "\\" + idSchedule + "coffee_brake_service.docx";
                templateFilePath = confCol.TrainingsCoffeeBrakeServiceFilePath;
            }

            if (template == "registration_form.docx")
            {
                resultFilePath = confCol.TrainingsDocsTargetPath + "\\" + idSchedule + "registration_form.docx";
                templateFilePath = confCol.TrainingsRegistrationFormFilePath;
            }

            //список для охраны с таблицей
            if (template == "members_list.docx")
            {
                resultFilePath = confCol.TrainingsDocsTargetPath + "\\" + idSchedule + "members_list.docx";
                templateFilePath = confCol.TrainingsMembersListFilePath;

                //получить расписание
                var schedule = (TrainingsSchedules) schedulesCol.GetItemById(idSchedule);
                if(schedule!=null)
                {
                    //таблица участников
                    var tablesParams = new DocReport.DocReportTablesParams
                                           {
                                               DataTable = schedule.MembersListTable,
                                               DocTableIndex = 2,
                                               StartRow = 2
                                           };
                    listTablesParams = new List<DocReport.DocReportTablesParams> {tablesParams};
                }
            }
            
            //формирование заполненного отчета
            var result = DocReport.CreateDoc(templateFilePath, resultFilePath, paramsList, listTablesParams);
            System.IO.File.Copy(resultFilePath, confCol.TrainingsDocsTempPath + "\\" + tempFileName);
            return File(confCol.TrainingsDocsTempPath + "\\" + tempFileName, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        }

        /// <summary>
        /// Отчеты по расписаниям
        /// </summary>
        /// <returns></returns>
        [CheckAccessAttribute]
        public ActionResult RequestsSchedulesReports()
        {
            var schedulesCol = new TrainingsSchedulesCollection();
            return View(schedulesCol.TrainingsSchedulesList);
        }

        public ActionResult RequestsSchedulesReportsPartal()
        {
            var schedulesCol = new TrainingsSchedulesCollection();
            return View(schedulesCol.TrainingsSchedulesList);
        }

        public ActionResult TrainingsSchedulesExportTo()
        {
            var schedulesCol = new TrainingsSchedulesCollection();
            return GridViewExtension.ExportToXls(TrainingsSchedulesExportGridViewSettings(), schedulesCol.TrainingsSchedulesList);
        }

        static GridViewSettings TrainingsSchedulesExportGridViewSettings()
        {
            var settings = new GridViewSettings();

            settings.Name = "gdTrainingsSchedule";
            settings.KeyFieldName = "IdTrainingsSchedule";
            settings.CallbackRouteValues = new { Controller = "TC", Action = "TrainingsSchedulesPartial" };
            settings.SettingsPager.PageSize = 20;
            settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;
            settings.Settings.ShowFilterRow = true;
            settings.Settings.ShowGroupPanel = true;

            //Тип 1)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingCoursesType;
                column.FieldName = "CourseTypeLocalazed";
            });

            //Рубрика 2)


            //Регион 3)

            //Город 4)

            //Название курса 5)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCourseName; ;
                column.FieldName = "CourseName";
            });

            //Дата 5.5)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsDate;
                //column.ColumnType = MVCxGridViewColumnType.DateEdit;
                column.FieldName = "PlannedDateExt";
            });

            //Кол-во дней 6)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsDuration;
                column.FieldName = "Duration";
            });

            //Заявленное кол-во чу 7)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCountRequested;
                column.FieldName = "ParticipantsCountRequested";
            });

            //Фактическое кол-во уч 8)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCountAvailable;
                column.FieldName = "ParticipantsCountAvailable";
            });

            //Название клиента 9)


            //тип курса 10)
            settings.Columns.Add(column =>
            {
                column.Caption = Resourses.Resourses.TrainingsCourseCost;
                column.FieldName = "CourseCost";
                column.Width = 40;
            });

            ////Добавление локализованного комбобокса
            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingsPlace";
            //    column.Caption = Resourses.TrainingsPlace;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        var placesCol = new CRM.Database.Model.TrainingsPlacesCollection();
            //        comboBoxProperties.DataSource = placesCol.TrainingsPlacesList;
            //        comboBoxProperties.TextField = "LocalizedName";
            //        comboBoxProperties.ValueField = "IdTrainingsPlace";
            //        comboBoxProperties.ValueType = typeof(int);
            //    }
            //});
            ////конец комбобокса

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingsPlace; ;
            //    column.FieldName = "LocationName";
            //});

            ////Добавление комбобоксов
            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingsTrainer";
            //    column.Caption = Resourses.TrainingsTrainer;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        var trainersCol = new CRM.Database.Model.TrainingsTrainersCollection();
            //        comboBoxProperties.DataSource = trainersCol.TrainingsTrainersList;
            //        comboBoxProperties.TextField = "Name";
            //        comboBoxProperties.ValueField = "IdTrainingsTrainer";
            //        comboBoxProperties.ValueType = typeof(int);
            //    }
            //});
            ////конец комбобокса

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingsTrainer;
            //    column.FieldName = "TrainerName";
            //});

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingsParticipantCost;
            //    column.FieldName = "ParticipantCoctExt";
            //});

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingsCountApproved;
            //    column.FieldName = "ParticipantsCountApproved";
            //});

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingsCountActual;
            //    column.FieldName = "ParticipantsCountActual";
            //});

            ////Добавление локализованного комбобокса
            //settings.Columns.Add(column =>
            //{
            //    column.FieldName = "IdTrainingCoursesStatus";
            //    column.Caption = Resourses.TrainingCoursesStatus;
            //    column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //    if (comboBoxProperties != null)
            //    {
            //        var statusesCol = new CRM.Database.Model.TrainingCoursesStatusesCollection();
            //        comboBoxProperties.DataSource = statusesCol.TrainingCoursesStatusesList;
            //        comboBoxProperties.TextField = "LocalizedName";
            //        comboBoxProperties.ValueField = "IdTrainingCoursesStatus";
            //        comboBoxProperties.ValueType = typeof(int);
            //    }
            //});
            ////конец комбобокса

            //settings.Columns.Add(column =>
            //{
            //    column.Caption = Resourses.TrainingCoursesStatus;
            //    column.FieldName = "CourseStatus";
            //});

            return settings;
        }

        #endregion
    }
}


//public ActionResult TrainingsRemoteRequestCreatePartial(int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    return PartialView(requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsRemoteRequestCreatePartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsNew, int key)
//{
//    participantsNew.IdUser = Request.LogonUserIdentity.Name;
//    participantsNew.IdTrainingsParticipantsStatus = 2;
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsAdd(participantsNew, key);
//    return PartialView("TrainingsRemoteRequestCreatePartial", requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsRemoteRequestCreatePartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsDel(participantsDel, key);
//    return PartialView("TrainingsRemoteRequestCreatePartial", requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsRemoteRequestCreatePartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsEdit(participantsDel, key);
//    return PartialView("TrainingsRemoteRequestCreatePartial", requestExt);
//}
//public ActionResult TrainingsPlannedRequestCreatePartial(int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    return PartialView(requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsPlannedRequestCreatePartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsNew, int key)
//{
//    participantsNew.IdUser = Request.LogonUserIdentity.Name;
//    participantsNew.IdTrainingsParticipantsStatus = 2;
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsAdd(participantsNew, key);
//    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsPlannedRequestCreatePartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsDel(participantsDel, key);
//    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
//}

//[HttpPost, ValidateInput(false)]
//public ActionResult TrainingsPlannedRequestCreatePartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
//{
//    var requestExt = DB.TrainingsRequestsExtDictionary[key];
//    DB.TrainingsParticipantsEdit(participantsDel, key);
//    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
//}
